<template>
	<div>
		<div class='index'>
  	  <header-top v-if='!isShare' :title="titleName" :page="pageName" :operation="headOpera" ></header-top>
  	  <div class='blank' v-if='!isShare'></div>
  	  <kline-swiper></kline-swiper>    
      <todaySimilar :unfoldFirst='!showPosition' ></todaySimilar>
      <div class='line'></div>
      <my-position v-if='showPosition' :show='holdData' :myPosition='myPosition' v-on:tryAgain='getHoldAndStock' :errMes='errMes'></my-position>
    </div>
    <div class='riskTip'>风险提示：相似K线计算结果不作为任何投资意见</div>
    <div class="to-top" v-show='manyStock' @click.stop="toTop"></div>
    <down-load v-if='isShare' :page='pageName'></down-load>
	</div>

</template>

<script>
import Constant from '@/common/constant'
import CommonUtil from '@/common/common.util'
import RemoteDAO from '@/common/RemoteDAO'
import HeaderTop from '@/components/common/HeaderTop'
import klineSwiper from '@/components/index/klineSwiper'
import myPosition from '@/components/index/myPosition'
import todaySimilar from '@/components/todaySimilar/index.vue'
import downLoad from '@/components/common/DownLoad'
export default {
  name: 'Index',
  data () {
    return {
      pageName: Constant.IndexPageName,
      headOpera: [Constant.Operation.SHARE], // 头部操作按钮
      titleName: '相似k线',
      showPosition: true,
      isShare: false,
      holdData: 'loading',
      myPosition: [],
      myPositionAll: [],
      stockCode: '',
      stockCodeAll: '',
      stockMarkets: '',
      getholdFlag: false,
      login: false,
      errMes: '出错了，点击重试',
      manyStock: false
    }
  },
  components: {
    HeaderTop,
    myPosition,
    todaySimilar,
    klineSwiper,
    downLoad
  },
  activated () {
    if (this.$store.state.getmobile === 1 && this.login === false) {
      this.init()
      this.login = true
    }
  },
  methods: {
    init () {
      if (this.isLogin()) {
        this.$store.dispatch('setGetmobile', 1)
        this.getHoldAndStock()
      } else {
        this.holdData = 'nodata'
      }
      this.maidian({id: '004001'})
    },
    isLogin () {
      let isLogin = Number(CommonUtil.getUrlParam('getmobile')) || this.$store.state.getmobile || Number(this.$route.query.getmobile)
      console.log('是否登录', isLogin)
      if (isLogin === 1) {
        localStorage.setItem('userCode', '0')
        return true
      } else {
        return false
      }
    },
    isSharefunc () {
      let share = CommonUtil.getUrlParam('url')
      if (typeof (share) !== 'undefined') {
        return true
      } else {
        return false
      }
    },
    getHoldAndStock () {
      this.holdData = 'loading'
      if (!this.getholdFlag) {
        console.log('adeline---hold')
        RemoteDAO.getStockAndHold().then(res => {
          let hold = res.data.hold
          let stock = res.data.stock
          if (hold.length === 0 && stock.length === 0) {
            this.holdData = 'nodata'
          } else {
            // let holdJson = this.changeToJson(hold, '持仓')
            let stockJson = this.changeToJson(stock, '自选')
            this.myPositionAll = stockJson
            this.getSimliarKLine()
          }
          this.getholdFlag = true
        }, err => {
          console.log(err)
        }).catch(e => {
          console.log(e)
        })
      } else {
        this.getSimliarKLine()
      }
    },
    changeToJson (arr, flag) {
      let myPosition = []
      for (let value of arr) {
        let item = Object.assign({}, {
          type: flag,
          stockCode: value.slice(2),
          marketType: value.slice(0, 2),
          stockName: '--'
        })
        myPosition.push(item)
        this.stockCodeAll = (this.stockCodeAll === '') ? item.stockCode : (this.stockCodeAll + ',' + item.stockCode)
        let marketType = item.marketType === 'SH' ? '1' : '2'
        this.stockMarkets = (this.stockMarkets === '') ? marketType : (this.stockMarkets + ',' + marketType)
      }
      return myPosition
    },
    getStockName () {
      RemoteDAO.getStockName(this.stockCode).then(res => {
//        res.data.find((value, index, arr) => {
//          this.myPosition[index].stockName = value.stockName
//        })
        res.data.map(data => {
          this.myPosition.map(stock => {
            if (stock.marketType + stock.stockCode === data.stockCode) {
              stock.stockName = data.stockName
            }
          })
        })
      })
    },
    getSimliarKLine () {
      // let self = this
      RemoteDAO.callUC12005212({stockCode: this.stockCodeAll, marketCode: this.stockMarkets}).then(res => {
        if (res.data.body.length === 0) {
          this.holdData = 'nodata'
        } else {
//          let myPositionMore = res.data.body.map(stock => {
//            const temp = this.myPositionAll.find(item => {
//              return item.stockCode === stock.STOCK_CODE
//            }) || {}
//            return Object.assign(stock, temp)
//          })
          let myPositionMore = res.data.body.map(stock => {
            let temp = {}
            this.myPositionAll.map(item => {
              if (item.stockCode === stock.STOCK_CODE) {
                temp = item
              }
            })
            return Object.assign(stock, temp)
          })
          // 删除相似K线数为0的股票
          let myPositionNosort = myPositionMore.filter(stock => {
            return stock.NUM_SIMILAR !== '0'
          })
          // 按持仓和自选进行排序
          this.myPosition = myPositionNosort.sort((x, y) => {
            return x.type === '持仓' ? -1 : 1
          })
          // 得出需要获取股票名称的股票列表
          for (let v of this.myPosition) {
            let marketType = v.marketType
            this.stockCode = (this.stockCode === '') ? marketType + v.STOCK_CODE : (this.stockCode + '|' + marketType + v.STOCK_CODE)
          }
          // 当删除无用的自选和持仓的股票后，如果股票数为0，就显示没有持仓的样式
          if (this.myPosition.length === 0) {
            this.holdData = 'nodata'
          } else {
            this.holdData = 'hasdata'
            this.getStockName()
          }
        }
      }, err => {
        this.holdData = 'error'
        this.errMes = err.message + '点击重试'
        console.warn(err)
      })
      .catch(error => {
        console.log(error)
      })
    },
    maidian (arg) {
      // 埋点
      let TDAPP = window.TDAPP
      let usercode = CommonUtil.getUrlParam('userCode') || ''
      if (arg.stockCode !== undefined) {
        TDAPP.onEvent(arg.id, '', {userCode: usercode, stockCode: arg.stockCode})
      } else {
        TDAPP.onEvent(arg.id, '', {userCode: usercode})
      }
      TDAPP.send()
    },
    toTop () {
      this.$nextTick(() => {
        let distance = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
        // 平滑滚动，时长500ms，每10ms一跳，共50跳
        let step = distance / 50
        smoothUp()
        function smoothUp () {
          if (distance > 0) {
            distance -= step
            document.body.scrollTop = distance
            document.documentElement.scrollTop = distance
            setTimeout(smoothUp, 5)
          } else {
            document.body.scrollTop = 0
            document.documentElement.scrollTop = 0
          }
        }
      })
    },
    judgeshow () {
      if (document.body.scrollTop > 120) {
        this.manyStock = true
      } else {
        this.manyStock = false
      }
    }
  },
  mounted () {
    if (!this.isSharefunc()) {
      this.init()
    } else {
      this.showPosition = false
      this.isShare = true
      this.maidian({id: '004015'})
    }
    window.addEventListener('scroll', this.judgeshow)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.judgeshow)
  }
}
</script>

<style scoped>
	.blank{
		height:88px;
		width:100%;
	}
	.index{
		background-color: #fff;
	}
	.line {
		height:14px;
		background-color: #f6f6f6;
	}
	.riskTip{
		color:#999999;
		font-size:24px;
		margin: 30px 0 32px 0;
	}
	.to-top {
    width: 90px;
    height: 90px;
    border-radius: 50%;
    color: #999999;
    position: fixed;
    bottom: 200px;
    right: 5%;
    background-image: url('~assets/images/totop.png');
    background-repeat: no-repeat;
    background-size: cover;
  }
</style>
